package com.satan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.satan.dto.PageDto;
import com.satan.entity.SysRole;
import com.satan.entity.SysUserRole;
import com.satan.mapper.SysRoleMapper;
import com.satan.service.SysRoleService;
import com.satan.service.SysUserRoleService;
import com.satan.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Demon
 * @description 针对表【sys_role】的数据库操作Service实现
 * @createDate 2023-10-03 20:53:34
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Map<String, Object> getPageList(PageDto pageDto) {
        String query = pageDto.getQuery().trim();
        Page<SysRole> pageResult = page(new Page<>
                (pageDto.getPageNum(), pageDto.getPageSize()), new QueryWrapper<SysRole>
                ().like(StringUtil.isNotEmpty(query), "name", query));
        List<SysRole> userList = pageResult.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", userList);
        resultMap.put("total", pageResult.getTotal());
        return resultMap;
    }

    @Override
    public boolean saveOrUpdateRole(SysRole sysRole) {
        if (sysRole.getId() == null || sysRole.getId() == -1) {
            sysRole.setId(null);
            return save(sysRole);
        } else {
            return updateById(sysRole);
        }
    }

    @Override
    @Transactional
    public boolean deleteRoleByIds(Long[] ids) {
        System.out.println("ids="+Arrays.toString(ids));
        boolean b1 = removeByIds(Arrays.asList(ids));
        boolean b2=true;
        List<SysUserRole> userRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>().in("role_id", ids));
        System.out.println("userRoleList = " + userRoleList);
        if (userRoleList.size()>0){
            b2 = sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", ids));
        }
        return b1 && b2;
    }
}




